Creating an App in Azure Ad to use as a Service Principal

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
Connect-AzureRmAccount

$name = 'ITOPS'
$location = 'westeurope'
$ResourceGroupName = 'itops.pt'

$app = New-AzureRmADApplication -DisplayName $name -IdentifierUris "https://$name.pt"
$sp = New-AzureRmADServicePrincipal -ApplicationId $app.ApplicationId

Start-Sleep -Seconds 20

New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName $sp.ApplicationId -ResourceGroupName $ResourceGroupName

#https://www.sabin.io/blog/adding-an-azure-active-directory-application-and-key-using-powershell/

function Create-AesManagedObject($key, $IV) 
{
  $aesManaged = New-Object -TypeName 'System.Security.Cryptography.AesManaged'
  $aesManaged.Mode = [System.Security.Cryptography.CipherMode]::CBC
  $aesManaged.Padding = [System.Security.Cryptography.PaddingMode]::Zeros
  $aesManaged.BlockSize = 128
  $aesManaged.KeySize = 256

  if ($IV) 
  {
    if ($IV.getType().Name -eq 'String')
    {
      $aesManaged.IV = [System.Convert]::FromBase64String($IV)
    }
    else 
    {
      $aesManaged.IV = $IV
    }
  }

  if ($key) 
  {
    if ($key.getType().Name -eq 'String')
    {
      $aesManaged.Key = [System.Convert]::FromBase64String($key)
    }
    else 
    {
      $aesManaged.Key = $key
    }
  }

  $aesManaged
}

function Create-AesKey()
{
  $aesManaged = Create-AesManagedObject
  $aesManaged.GenerateKey()
  [System.Convert]::ToBase64String($aesManaged.Key)
}

#Create the 44-character key value
$keyValue = Create-AesKey

$appsecret = New-AzureRmADAppCredential -ApplicationId $sp.ApplicationId -Password (ConvertTo-SecureString ($keyValue) -AsPlainText -Force) -EndDate (Get-Date).AddMonths(12)

"********
copy this down , you need it later  it's the app secret key   >>    " + $keyValue

'This is the application / service principal ID . copy this too >>  ' +  $app.ApplicationId